package com.socialuni.sdk.user.phone;

import com.socialuni.sdk.constant.status.UserStatus;
import com.socialuni.sdk.exception.SocialBusinessException;
import com.socialuni.sdk.exception.SocialParamsException;
import com.socialuni.sdk.model.DO.user.SocialPhoneNumDO;
import com.socialuni.sdk.model.DO.user.UserDO;
import com.socialuni.sdk.store.SocialUserPhoneStore;
import com.socialuni.sdk.utils.PhoneNumUtil;
import com.socialuni.sdk.utils.UserUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

//授权用户信息
@Service
public class SocialPhoneNumCheck {
    @Resource
    SocialUserPhoneStore socialUserPhoneStore;

    //业务校验,发送验证码调用、手机号登录调用、绑定手机号调用
    public SocialPhoneNumDO checkPhoneNum(String phoneNum, UserDO mineUser) {
        PhoneNumUtil.checkPhoneNum(phoneNum);
        SocialPhoneNumDO socialUserPhoneDO = this.checkPhoneNumberUsable(phoneNum, mineUser);
        if (mineUser != null) {
            this.checkUserHasBindPhoneNum(mineUser);
        }
        return socialUserPhoneDO;
    }

    //校验手机号是否可用
    private SocialPhoneNumDO checkPhoneNumberUsable(String phoneNum, UserDO mineUser) {
        SocialPhoneNumDO socialUserPhoneDO = socialUserPhoneStore.findByPhoneNum(phoneNum);
        if (socialUserPhoneDO != null) {
            UserDO phoneUser = UserUtils.get(socialUserPhoneDO.getUserId());
            //如果手机号违规，则返回手机号不可用
            if (phoneUser.getStatus().equals(UserStatus.violation)) {
                throw new SocialBusinessException("手机号不可用");
            }
            //用户不为空才校验手机号是否已被使用
            if (mineUser != null) {
                throw new SocialBusinessException("手机号已被绑定");
            }
        }
        return socialUserPhoneDO;
    }

    //判断用户是否已绑定手机号
    private void checkUserHasBindPhoneNum(UserDO mineUser) {
        SocialPhoneNumDO socialUserPhoneDO = socialUserPhoneStore.findByUserId(mineUser.getId());
        if (socialUserPhoneDO != null) {
            throw new SocialParamsException("用户已绑定手机号");
        }
    }
}
